package org.water.common.shiro.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.water.base.entity.ResultBaseBean;
import org.water.common.bind.method.ReulstFormatReturnValueHandler;

import com.alibaba.fastjson.JSON;

/**
 * 用户认证
 * 
 * @author qzy
 *
 */
public class UserAuthenticationFilter extends FormAuthenticationFilter {

	public UserAuthenticationFilter() {
		// TODO Auto-generated constructor stub
	}

	private static Logger logger = LogManager.getLogger(UserAuthenticationFilter.class);

	/** 主要是针对登入成功的处理方法。对于请求头是AJAX的之间返回JSON字符串。 **/
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		return super.onLoginSuccess(token, subject, request, response);
	}

	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {// ajax请求
			try {
				PrintWriter out = response.getWriter();
				String message = e.getClass().getSimpleName();
				ResultBaseBean bean=new ResultBaseBean();
			    ResultBaseBean result=new ResultBaseBean();
			    result.setSuccess(false);
			    bean.setData(result);
				if ("IncorrectCredentialsException".equals(message)) {
					result.setMsg("密码错误");
				} else if ("UnknownAccountException".equals(message)) {
					result.setMsg("账号不存在");
				} else if ("LockedAccountException".equals(message)) {
					result.setMsg("账号被锁定");
				} else {
					result.setMsg("未知错误");
				}
				out.println(ReulstFormatReturnValueHandler.generateJson(result));
				out.flush();
				out.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return false;
		}
		return super.onLoginFailure(token, e, request, response);
	}
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {// ajax请求
		    //设置头 便于ajax前端处理
			String loginUrl=getLoginUrl();
			HttpServletResponse httpServletResponse = (HttpServletResponse)response;
			if(httpServletResponse!=null)
			{
				String ctx=((HttpServletRequest) request).getContextPath();
				httpServletResponse.setHeader("redirect", "true");
				httpServletResponse.setHeader("contentpath", ctx+loginUrl);
			}
			
			//输出未授权信息
			PrintWriter out = response.getWriter();
			ResultBaseBean bean=new ResultBaseBean();
			ResultBaseBean result=new ResultBaseBean();
			result.setMsg("未授权，不能进行访问！");
			result.setSuccess(false);
			bean.setData(result);
			String accept=((HttpServletRequest) request).getHeader("Accept");
			if(accept.contains("application/xml") || accept.contains("text/xml"))
			{
				response.setContentType("application/xml;charset=UTF-8");
				out.write(ReulstFormatReturnValueHandler.generateXml(bean));
			}
			else if(accept.contains("application/json") || accept.contains("text/json"))
			{
				response.setContentType("application/json; charset=UTF-8");
				out.write(ReulstFormatReturnValueHandler.generateJson(bean));
			}
			else
			{
				response.setContentType("text/plain; charset=UTF-8");
				out.write(ReulstFormatReturnValueHandler.generateJson(bean));
			}
			out.flush();
			out.close();
			
			return false;
		}
		return super.onAccessDenied(request, response);
	}
}
